package com.example.test.creash;

import android.app.Application;
import android.content.Context;
import android.util.Log;

/**
 * @auth: njb
 * @date: 2024/5/22 10:20
 * @desc: 描述
 */
public class CrashManager implements Thread.UncaughtExceptionHandler{
    public static final String TAG = "CrashHandler";
    // CrashHandler实例
    private static CrashManager instance;
    // 程序的Context对象
    private Application application;
    // 系统默认的UncaughtException处理类
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    /**
     * 保证只有一个CrashHandler实例
     */
    private CrashManager(Context context) {
        application = (Application) context.getApplicationContext();
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static CrashManager getInstance(Context context) {
        CrashManager inst = instance;
        if (inst == null) {
            synchronized (CrashManager.class) {
                inst = instance;
                if (inst == null) {
                    inst = new CrashManager(context.getApplicationContext());
                    instance = inst;
                }
            }
        }
        return inst;
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        Log.e(TAG,ex.toString());
        mDefaultHandler.uncaughtException(thread, ex);
    }

}
